import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../views/login.vue'
import reg from '../views/reg.vue'
import main from '../views/main.vue'
import store from '../store/index.js'
import home from '../views/menus/home.vue'
import userinfo from '../views/menus/user-info.vue'
import UserAvatar from '../views/menus/UserAvatar.vue'
import UserPwd from '../views/menus/UserPwd.vue'
Vue.use(VueRouter)
const router = new VueRouter({
  routes: [
    { path: '/login', component: login },
    { path: '/reg', component: reg },
    {
      path: '/',
      component: main,
      redirect: '/home',
      children: [{ path: 'home', component: home }, { path: 'user-info', component: userinfo }, { path: 'user-avatar', component: UserAvatar }, { path: 'user-pwd', component: UserPwd }]
    }
  ]
})
// 路由守卫,判断是否有token值
router.beforeEach((to, from, next) => {
  if (to.path === '/login' || to.path === '/reg') {
    next()
  } else {
    const token = store.state.user.token
    if (token) {
      next()
    } else { next('/login') }
  }
})
export default router
